package com.yu.filter;

import com.common.constant.JwtProperties;
import com.common.context.UserContext;
import com.common.exception.CodeAndMsg;
import com.common.exception.JavaSmException;
import com.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author 路亚
 * @version 0.1
 * @className AuthGlobalFilter
 * @description
 * @date 2024/12/11 11:47
 * @since jdk11
 */
@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final JwtProperties jwtProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        // 如果是登录接口，直接放行
        if (request.getURI().getPath().contains("login")) {
            return chain.filter(exchange);
        }
        // webTokenName是普通用户登录生成的token
        List<String> webTokenList = request.getHeaders().get(jwtProperties.getWebTokenName());
        List<String> adminTokenList = request.getHeaders().get(jwtProperties.getAdminTokenName());
        if (CollectionUtils.isEmpty(webTokenList) && CollectionUtils.isEmpty(adminTokenList)) {
            throw new JavaSmException(CodeAndMsg.TOKEN_NOT_FOUND);
        }else if (!CollectionUtils.isEmpty(webTokenList)){
            String token = webTokenList.get(0);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getWebSecretKey(), token);
            Long webId = claims.get(jwtProperties.getWebIdName(), Long.class);
            return chain.filter(exchange.mutate().request(exchange.getRequest().mutate().header("user_id", webId.toString()).build()).build());
        }else if (!CollectionUtils.isEmpty(adminTokenList)){
            String token = adminTokenList.get(0);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            Long adminId = claims.get(jwtProperties.getAdminIdName(), Long.class);
            return chain.filter(exchange.mutate().request(exchange.getRequest().mutate().header("user_id", adminId.toString()).build()).build());
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
